package by.averianov.discounta.webapp.page.loginpage.loginactivate;

import javax.inject.Inject;

import org.apache.wicket.Application;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.averianov.discounta.datamodel.UserAccount;
import by.averianov.discounta.datamodel.UserProfile;
import by.averianov.discounta.services.UserService;
import by.averianov.discounta.webapp.page.BaseLayout;

public class LoginActivatePage  extends BaseLayout {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoginActivatePage.class);
	
	private PageCreator pageCreator;
	private UserAccount userAccount;
	private UserProfile userProfile;

	// user - {id, userEmail, userPassword, accessGroupId, userFirstName, userLastName, phoneNumber}
	public LoginActivatePage(UserAccount userAccount, UserProfile userProfile, PageCreator pageCreator) {
		super(null);
		this.pageCreator = pageCreator;
		this.userAccount = userAccount;
		this.userProfile = userProfile;
	}

	@Inject
	private UserService userService;
	
	@Override
	protected void onInitialize() {
		super.onInitialize();
		
		final TextField<String> EnterActivateCodeText = new TextField<String>("activateCode", Model.of(""));
		
		Form<?> form = new Form<Void>("activateCodeForm") {
			@Override
			public void onSubmit() {
				String resultingActivateCode = EnterActivateCodeText.getModelObject();
				String userActivateCode = userAccount.getActivateCode();
				if (resultingActivateCode.equals(userActivateCode)) {
					userAccount.setUserStatus(true);
					userService.saveOrUpdateUser(userProfile, userAccount);
					info(new ResourceModel("p.login.useractivate").getObject());
					setResponsePage(pageCreator.createPage());
				} else {
					error(new ResourceModel("p.error.logindeactivated").getObject());
				}
				
			}
		};		 
		add(form);				
		Label labelEnterActivateCode = new Label("labelEnterActivateCode",  new ResourceModel("p.enteractivatecode.titleactivatecode"));
		form.add(labelEnterActivateCode);
		
		form.add(EnterActivateCodeText);
		
		form.add(new Label("labelSave", getButtonActivate()));
		
		Link linkCancel = new Link("linkCancel"){
			@Override
			public void onClick() {
				setResponsePage(pageCreator.createPage());
				
			}
		};
		linkCancel.add(new Label("labelCancel", getButtonCancel()));
		form.add(linkCancel);
	}
}